package com.ay.weixin.fdc.front.usercenter.event.manager;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.intercepter.Before;
import org.lizar.controller.loader.BasicLoader;
import org.lizar.controller.loader.EventLoader;
import org.lizar.controller.loader.FilePostForm;
import org.lizar.ioc.Container;
import org.lizar.json.JObject;
import org.lizar.util.MyMath;
import org.lizar.util.StringHelper;

import com.ay.weixin.config.AppConfig;
import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.types.UserStatus;
import com.ay.weixin.config.types.UserType;
import com.ay.weixin.fdc.boss.autoreply.event.ReplySetting;
import com.ay.weixin.fdc.boss.user.db.FDCAgentDao;
import com.ay.weixin.fdc.boss.user.domain.Activity;
import com.ay.weixin.fdc.boss.user.domain.FDCAgent;
import com.ay.weixin.fdc.boss.user.domain.FDCUserCenter;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;
import com.ay.weixin.fdc.boss.user.domain.UserCenter;
import com.ay.weixin.fdc.boss.user.domain.UserWeiXinInfo;
import com.ay.weixin.fdc.boss.yongjin.db.IbatisCashFlow;
import com.ay.weixin.fdc.boss.yongjin.domain.CashFlow;
import com.ay.weixin.fdc.front.usercenter.event.UserEvent;
import com.ay.weixin.fdc.front.usercenter.event.UserInfoAccess;
import com.ay.weixin.templatereply.domain.ReplyMsg;
import com.ay.weixin.templatereply.domain.TemplateReply;

/**
 * 
 * 
 * */
public class Register extends Event implements Before{
	private FDCAgentDao user_dao;
	private IbatisCashFlow cash_dao;
	private UserEvent user_event;
	private UserInfoAccess user_access;
	private FDCUserCenter user_center;
	private com.ay.weixin.fdc.front.usercenter.event.old.Register register_old;
	
	@Override
	public void init_property() throws Exception {
		user_dao=Container.get(FDCAgentDao.class);
		cash_dao=Container.get(IbatisCashFlow.class);
		user_event=Container.get(UserEvent.class);
		register_old=Container.get(com.ay.weixin.fdc.front.usercenter.event.old.Register.class);
		user_access=Container.get(UserInfoAccess.class);
		user_center=Container.get(FDCUserCenter.class);
		
	}

	
	@Override
	public void before(BasicLoader bl) throws ServletException, IOException {
		long wxproject_id=bl.queryPathInt(2);
		bl.setAttr("need_upload_business_card", ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_upload_business_card"));
		bl.setAttr("need_upload_ID_card", ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_upload_ID_card"));
		bl.setAttr("need_id_card_no",ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_id_card_no"));
		bl.setAttr("need_invate_code", ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_invate_code"));
		bl.setAttr("user_type",UserType.manager.name());
		
	}
	
	@Override
	public String default_handling_path() {
		return "/fdc/register/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		long project_id=el.queryPathInt(2);
		System.out.println("project_id:"+project_id);
		
		handle(el,project_id);
	}
	
	public void handle(EventLoader el,long wxproject_id) throws ServletException, IOException {
		if(!el.getBool("is_weixin")&&ProjectConfig._bool(wxproject_id,"sys.weixin_only")){
			el.text("invalid visit");
			return;
		}
		if(el.getSessionAttr("user")!=null){
			el.response_to_root("/fdc/usercenter/"+wxproject_id);
			return;
		}
		
		//微信授权
		UserWeiXinInfo weixin_info=el.getSessionAttr("weixin_info",UserWeiXinInfo.class);
		if(weixin_info==null){
			if(StringHelper.equals(el.getAttr("user_type"), UserType.old.name())){
				user_access.open_id_check(el,Keys.getStr("forward.user_register_old_default_url"),wxproject_id);
			}else{
				user_access.open_id_check(el,Keys.getStr("forward.user_register_default_url"),wxproject_id);
			}
			return;
		}
		
		UserBasic user=null;
		try {
			user=user_dao.getById(weixin_info.getUser_id());
		} catch (SQLException e) {
			e.printStackTrace();
			view(el,wxproject_id);
			return;
		}
		
		if(user!=null){
			el.setSessionAttr("user",user);
			user_center.setSession(user.getId(), el.getSession());
			el.response_to_root("/fdc/usercenter/"+wxproject_id);
			return;
		}
		
		//已注册，直接登陆
		if(weixin_info.getRegistered()==UserWeiXinInfo.REGISTERED_TRUE){
			if(StringHelper.equals(el.getAttr("user_type"),UserType.old.name())){
				el.response_to_root("/fdc/login/old"+wxproject_id);
			}else{
				el.response_to_root("/fdc/login/"+wxproject_id);
			}
			return;
		}
		
		if(StringHelper.equals(el.getAttr("user_type"), "old")){
			register_old.try_register(el,wxproject_id);
		}else{
			try_register(el,wxproject_id);
		}
	}
	
	private void try_register(EventLoader el,long wxproject_id) throws IOException, ServletException{
		if(el.queryPathCheck(3,"submit")){
			submit(el,wxproject_id);
		}else{
			view(el,wxproject_id);
		}
	}
	
	private void view(EventLoader el,long wxproject_id) throws IOException, ServletException{
		UserEvent.load_vcode_check(el,wxproject_id);
		el.template("/WEB-INF/template/app/"+wxproject_id+"/fdc/register.vm");
	}
	
	private void submit(EventLoader el,long wxproject_id) throws IOException, ServletException{
		if(!el.isMultipartContent()){
			el.text("invalid visit.");
			return;
		}
		UserEvent.inc_vcode_check(el,wxproject_id);
		FilePostForm file=el.parseFilePostForm(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);
		file.setAllParamToAttr(el);
		String name=file.getStr("name");
		String password=file.getStr("password");
		String phone=file.getStr("phone");
		String from_invite_code=file.getStr("invite_code");
		String id_card_no=file.getStr("id_card_no");
		String vcode=file.getStr("vcode");
		file.setAllParamToAttr(el);
		String msg=null;
		if(file.getErrorMsg()!=null){
	        msg=file.getErrorMsg();
	        el.setAttr("msg",msg);
	        view(el,wxproject_id);
	       return;
	    }
		
		FileItem business_card=null;
		FileItem ID_card=null;
		List<FileItem> items=file.getFileItems();
		for(FileItem it:items){
			if(it.getFieldName().toLowerCase().equals("business_card")){
				business_card=it;
			}else if(it.getFieldName().toLowerCase().equals("id_card")){
				ID_card=it;
			}
		}
		
		boolean need_vcode=el.getSessionAttr("tel_vcode", 0)>=ProjectConfig.getInt(wxproject_id,"fdc_usercenter.vcode_used_error_in_times");
		System.out.println("11input_code:"+vcode+",expected_code:"+el.getSessionAttr("vcode"));
		if(need_vcode&&el.getSessionAttr("vcode")!=null&&!StringHelper.equals(vcode.toLowerCase(), el.getSessionAttr("vcode").toString().toLowerCase())){
			System.out.println("22input_code:"+vcode+",expected_code:"+el.getSessionAttr("vcode"));
			msg=el.i18("login.vcode_invalid");
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		
		System.out.println(name+"name:"+name.length());
		if(StringHelper.isNull(name)||name.length()>Keys.getInt("fdc_usercenter.register_name_max_length")||name.length()<Keys.getInt("fdc_usercenter.register_name_min_length")){
			msg=String.format(el.i18("fdc_usercenter.name.not.valid"), Keys.getInt("fdc_usercenter.register_name_min_length"),Keys.getInt("fdc_usercenter.register_name_max_length"));
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		
		if(StringHelper.isNull(password)||!StringHelper.isLong(password)||password.length()>Keys.getInt("fdc_usercenter.register_password_max_length")||password.length()<Keys.getInt("fdc_usercenter.register_password_min_length")){
			msg=String.format(el.i18("fdc_usercenter.password.not.valid"), Keys.getInt("fdc_usercenter.register_password_min_length"),Keys.getInt("fdc_usercenter.register_password_max_length"));
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		
		if(StringHelper.isNull(phone)){
			msg=String.format(el.i18("fdc_usercenter.phone.not.valid"), Keys.getInt("fdc_usercenter.register_phone_length"));
			el.setAttr("msg",msg);
	        view(el,wxproject_id);
			return;
		}
		
		try {
			if(user_dao.phoneExists(wxproject_id,phone)){
				msg=el.i18("fdc_usercenter.phone.already.exists");
				el.setAttr("msg",msg);
			    view(el,wxproject_id);
				return;
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
			el.setAttr("msg",el.i18("fdc_usercenter.server_error"));
	        view(el,wxproject_id);
			return;
		}
		
		
		
		File business_card_file=null;
		File ID_card_file=null;
		String business_card_file_name=null;
		String ID_card_file_name=null;
		
		FDCAgent from_user=null;
		
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_invate_code")&&StringHelper.isNotNull(from_invite_code)){
			try {
				from_user=user_dao.getByInviteCode(from_invite_code);
				if(from_user==null){
					msg=String.format(el.i18("fdc_usercenter.invite_code.notvalid"));
					el.setAttr("msg",msg);
				    view(el,wxproject_id);
					return;
				}
			} catch (SQLException e) {
				e.printStackTrace();
				el.setAttr("msg",el.i18("fdc_usercenter.server_error"));
		        view(el,wxproject_id);
				return;
				
			}
		}
		
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_id_card_no")){
			try {
				msg=UserEvent.IDCardValidate(id_card_no);
			} catch (ParseException e) {
				msg=String.format(el.i18("fdc_usercenter.id_card_no.notvalid"));
				el.setAttr("msg",msg);
			    view(el,wxproject_id);
				return;
			}
			if(StringHelper.isNull(id_card_no)){
				msg=String.format(el.i18("fdc_usercenter.id_card_no.notvalid"));
				el.setAttr("msg",msg);
			    view(el,wxproject_id);
				return;
			}else{
				try {
					if(user_dao.getByIDCardNo(wxproject_id,id_card_no)!=null){
						msg=String.format(el.i18("fdc_usercenter.id_card_no.exists"));
						el.setAttr("msg",msg);
					    view(el,wxproject_id);
						return;
					}
				} catch (SQLException e) {
					e.printStackTrace();
					el.setAttr("msg",el.i18("fdc_usercenter.server_error"));
			        view(el,wxproject_id);
					return;
				}
			}
		}
		
		FDCAgent user=new FDCAgent();
		user.setName(name);
		user.setPassword(MyMath.encryptionWithMD5(password));
		user.setPhone(phone);
		user.setFrom_invite_code(from_invite_code);
		user.setType(UserType.manager.name());
		user.setId_card_no(id_card_no);
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_verify_manually")){
			user.setProfile_verify(UserBasic.PROFILE.NOT_VERIFY.getValue());
			user.setStatus(UserStatus.apply.name());
		}else{
			user.setProfile_verify(UserBasic.PROFILE.VERIFIED.getValue());
			user.setStatus(UserStatus.ok.name());
		}
		
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_upload_business_card")){
			if(business_card!=null){
				if(AppConfig.img_support_fix.get(StringHelper.postfix(business_card.getName().toLowerCase()))==null){
					msg=String.format(el.i18("fdc_usercenter.need_upload_business_card"),Keys.getStr("fdc_usercenter.image_post_fix_support"));
					el.setAttr("msg",msg);
			        view(el,wxproject_id);
					return;
				}else{
					business_card_file_name=UUID.randomUUID().toString()+".jpg";
			        String file_path=ReplySetting.getImagePath(el,wxproject_id, business_card_file_name);
			        business_card_file=new File(file_path);
			        if(!business_card_file.getParentFile().exists()){
			        	business_card_file.getParentFile().mkdirs();
			        }
			        try {
			        	business_card.write(business_card_file);
					} catch (Exception e) {
						e.printStackTrace();
						msg=el.i18("fdc_usercenter.image.save.failed");
						el.setAttr("msg",msg);
						view(el,wxproject_id);
						return;
					}
				}
			}else{
				if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_forced_business_card")){
					msg=String.format(el.i18("fdc_usercenter.need_upload_business_card"),Keys.getStr("fdc_usercenter.image_post_fix_support"));
					el.setAttr("msg",msg);
			        view(el,wxproject_id);
					return;
				}
				
			}
		}
		
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_upload_ID_card")){
			if(ID_card!=null){
				if(AppConfig.img_support_fix.get(StringHelper.postfix(ID_card.getName().toLowerCase()))==null){
					msg=String.format(el.i18("fdc_usercenter.need_upload_ID_card"),Keys.getStr("fdc_usercenter.image_post_fix_support"));
					el.setAttr("msg",msg);
			        view(el,wxproject_id);
					return;
				}else{
					ID_card_file_name=UUID.randomUUID().toString()+".jpg";
			        String file_path=ReplySetting.getImagePath(el,wxproject_id, ID_card_file_name);
			        ID_card_file=new File(file_path);
			        try {
			        	ID_card.write(ID_card_file);
					} catch (Exception e) {
						e.printStackTrace();
						msg=el.i18("fdc_usercenter.image.save.failed");
						el.setAttr("msg",msg);
						view(el,wxproject_id);
						return;
					}
				}
			}else{
				if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_forced_ID_card")){
					msg=String.format(el.i18("fdc_usercenter.register_forced_ID_card"),Keys.getStr("fdc_usercenter.image_post_fix_support"));
					el.setAttr("msg",msg);
			        view(el,wxproject_id);
					return;
				}
			}
		}
		if(business_card!=null)user.setBusiness_card_url(ReplySetting.getRelatImagePath(el,wxproject_id, business_card_file_name));
		if(ID_card!=null)user.setID_card_url(ReplySetting.getRelatImagePath(el,wxproject_id, ID_card_file_name));
		user.setCreate_time(new Date(System.currentTimeMillis()));
		user.setRegister_reward(UserBasic.REGISTER_REWORD_FALSE);
		user.setWxproject_id(wxproject_id);
		try{
			user_dao.insert(user);
			user=user_dao.getByPhone(wxproject_id,phone);
			user.setInvite_code(UserCenter.getInviteCode(user.getId()));
			user_dao.updateInviteCode(user.getId(),user.getInvite_code());
		}catch(Exception e){
			e.printStackTrace();
			el.setAttr("msg",el.i18("fdc_usercenter.server_error"));
			
			if(ID_card_file!=null){
				ID_card_file.delete();
			}
			
			if(business_card_file!=null){
				business_card_file.delete();
			}
			
	        view(el,wxproject_id);
			return;
		}
		
		UserWeiXinInfo weixin_info=el.getSessionAttr("weixin_info",UserWeiXinInfo.class);
		if(weixin_info!=null){
			if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_verify_manually")){
				reply(wxproject_id,"账户注册成功","，请等待我们的工作人员为您审核",weixin_info.getId(),user);
			}else{
				reply(wxproject_id,"账户注册成功","，您现在可以推荐客户啦",weixin_info.getId(),user);
			}
		}
		
		if(!ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_need_verify_manually")){
			register_income(el,wxproject_id,from_invite_code,user,from_user);
		}
		
		el.setSessionAttr("user",user);
		UserEvent.clean_vcode(el);
		UserEvent.setSessionTimeOut(el);
		el.setSessionAttr("registered",true);
		user_event.update_weixin(el,user.getId());
		user_center.setSession(user.getId(), el.getSession());
		el.response_to_root("/fdc/usercenter/"+wxproject_id);
	}
	
	/**
	 * 
	 * {{first.DATA}}\n\n账户名称：{{name.DATA}}\n开通时间：{{time.DATA}}\n{{remark.DATA}}
	 * 
	 * */
	public static void reply(long wxproject_id,String event,String _msg,String ropenid,FDCAgent user_basic){
		if(StringHelper.isNull(ropenid))return;
		JObject params=new JObject();
		JObject first=new JObject();
		first.put("value", event);
		first.put("color", ReplyMsg.BLUE);
		params.put("first", first);
		
		JObject name=new JObject();
		name.put("value", user_basic.getName());
		name.put("color", ReplyMsg.BLUE);
		params.put("name", name);
		
		JObject time=new JObject();
		time.put("value", Calendar.getInstance().getTime().toLocaleString());
		time.put("color", ReplyMsg.BLUE);
		params.put("time", time);
		
		
		JObject remark=new JObject();
		remark.put("value","状态："+UserBasic.PROFILE.getStatus(user_basic.getProfile_verify()).getDesc()+_msg);
		first.put("color", ReplyMsg.LIGHT_BLACK);
		params.put("remark", remark);
		
		ReplyMsg msg=new ReplyMsg();
		msg.setMsg_link("");
		msg.setOpenid(ropenid);
		msg.setWxproject_id(wxproject_id);
		msg.setTemplate_id(ProjectConfig.getStr(wxproject_id,"fdc_usercenter.account_open_template_msg_id"));
		msg.setTopcolor(ReplyMsg.BLUE);
		msg.setData_params(params);
		TemplateReply.asyReply(msg);
	}
	
	
	public void register_income(EventLoader el,long wxproject_id,String from_invite_code,FDCAgent user,FDCAgent from_user){
		float register_value=0;
		float invitor_value=0;
		
		try {
			if(user_dao.hasRegisterRecord(user.getId())){
				return;
			}
			user.setRegister_reward(UserBasic.REGISTER_REWARD_TRUE);
			user_dao.updateRegisterReward(user.getId());
		} catch (SQLException e1) {
			e1.printStackTrace();
			return;
		}
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_benifit_for_new_commer")){
			if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_confirm_benifit")){
				register_value=ProjectConfig.getFloat(wxproject_id,"fdc_usercenter.register_benifit_value");
			}else{
				String result=Activity.activity_cash_rules(ProjectConfig.getStr(wxproject_id,"fdc_usercenter.register_invate_benifit_rules"));
				try{
					register_value=Float.parseFloat(result);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			CashFlow mycash=new CashFlow();
			mycash.setCash(register_value);
			mycash.setFrom_user_id(0);
			mycash.setReason(Keys.getStr("fdc_usercenter.register_return"));
			mycash.setTimestamp(System.currentTimeMillis());
			mycash.setUser_id(user.getId());
			mycash.setFlow_in(CashFlow.FLOW_IN);
			mycash.setIn_status(CashFlow.IN_STATUS_IN);
			try {
				cash_dao.insert(mycash);
			} catch (SQLException e) {
				e.printStackTrace();
				el.setSessionAttr("user",user);
			}
			el.setAttr("cash",mycash);
		}
		
		if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_invate_benifit")&&from_user!=null){
			if(ProjectConfig._bool(wxproject_id,"fdc_usercenter.register_confirm_benifit")){
				invitor_value=ProjectConfig.getFloat(wxproject_id,"fdc_usercenter.register_invate_benifit_value");
			}else{
				String result=Activity.activity_cash_rules(ProjectConfig.getStr(wxproject_id,"fdc_usercenter.register_invate_benifit_rules"));
				try{
					invitor_value=Float.parseFloat(result);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			CashFlow return_cash=new CashFlow();
			return_cash.setCash(invitor_value);
			return_cash.setFrom_user_id(user.getId());
			String name=user.getName();
			if(name.length()==1){
				name="*"+name;
			}else{
				name="*"+user.getName().substring(1);
			}
			return_cash.setReason(String.format(Keys.getStr("fdc_usercenter.register_invite_return"),name));
			return_cash.setTimestamp(System.currentTimeMillis());
			return_cash.setUser_id(from_user.getId());
			return_cash.setFlow_in(CashFlow.FLOW_IN);
			return_cash.setIn_status(CashFlow.IN_STATUS_IN);
			try {
				cash_dao.insert(return_cash);
			} catch (SQLException e) {
				e.printStackTrace();
				el.setSessionAttr("user",user);
			}
		}
		
	}
	
}
